package com.lcxw.hxzbadmin.controller.admincontroller;

import com.lcxw.hxzbcommon.entity.ErrorCode;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.annotation.Resource;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.lcxw.hxzbadmin.entity.pojo.AdminUser;
import com.lcxw.hxzbadmin.entity.requestbean.AdminLoginRequestParams;
import com.lcxw.hxzbadmin.service.baseservice.AdminUserService;
import com.lcxw.hxzbapi.entity.response.Response;
import com.lcxw.hxzbcommon.common.AesCBCUtil;
import com.lcxw.hxzbcommon.common.RedisUtils;

@RestController
@RequestMapping("/admin")
@CrossOrigin
public class AdminLoginController {

    Logger logger = LoggerFactory.getLogger(AdminLoginController.class);

    @Resource
    AdminUserService adminUserService;

    @Resource
    RedisUtils redisUtils;

    @SneakyThrows
    @PostMapping("/login")
    public Response adminLogin(@RequestBody AdminLoginRequestParams adminLoginParams) {
        logger.info("admin {} login...", adminLoginParams.getAdminName());

        String adminName = adminLoginParams.getAdminName();
        String password = adminLoginParams.getPassword();
        password = AesCBCUtil.getInstance().encrypt(password);
        String lastLoginIp = adminLoginParams.getLastLoginIp();

        AdminUser adminUser;
        String token;

        Response response = new Response();

        try {
            adminUser = adminUserService.queryAdminByName(adminName);
            if (null == adminUser || !password.equals(adminUser.getPassword())) {
                return Response.common(logger, "admin登录失败，用户不存在或密码错误。", ErrorCode.INVALID_PARAM,
                    "admin login failed, user not exist or wrong password", null);
            }

            //admin登录成功，更新admin的登录时间，保存数据库。
            adminUser.setLastLogIp(lastLoginIp);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String lastLoginTime = sdf.format(new Date());
            adminUser.setLastLogTime(lastLoginTime);

            adminUserService.updateAdminByName(adminUser);

            //构造token 使用adminName和时间戳，生成唯一token
            String tokenKey =
                adminUser.getAdminName() + ":" + Calendar.getInstance().getTimeInMillis();
            token = AesCBCUtil.getInstance().encrypt(tokenKey);

            //登录成功后，adminName，和对应的token存到redis, admin 用户的token在redis中只能保存4小时
            redisUtils
                .string_set("admin:" + adminUser.getAdminName() + ":token", token, 60 * 60 * 10);
            logger.info("admin name: {} 登录成功,token为 : {}", adminUser.getAdminName(), token);

            String adminType = adminUser.getAdminType();

            Map<String, Object> data = new LinkedHashMap<>();
            data.put("token", token);
            data.put("adminType", adminType);
            response.setCode(0);
            response.setDesc("success");
            response.setData(data);

        } catch (Exception e) {
            return Response.dbFail(logger, "db operate with admin user");
        }

        return response;
    }

}
